// Reviewer.js
import React, { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import Web3 from 'web3';
import MaterialListABI from '../contract/ABIs/MaterialList.json'; // 材料列表合约 ABI
import ReviewerListABI from '../contract/ABIs/ReviewerList.json'; // 审核员列表合约 ABI
import ReviewerABI from '../contract/ABIs/Reviewer.json'; // 审核员合约 ABI
import UserListABI from '../contract/ABIs/UserList.json'; // 用户列表合约 ABI
import { Table, Modal } from 'antd';
import UserListAddress from '../contract/ADDRESSes/UserListAddress'; // 用户列表合约地址
import MaterialListAddress from '../contract/ADDRESSes/MaterialListAddress'; // 材料列表合约地址
import ReviewerListAddress from '../contract/ADDRESSes/ReviewerListAddress'; // 审核员列表合约地址
import ActivityListAddress from '../contract/ADDRESSes/ActivityListAddress.js'; // 活动列表合约地址
import ReviewerNavBar from './nav/ReviewerNavBar.js';
import gb from '../static/bootstrap/images/gb.svg';
import us from '../static/bootstrap/images/us.svg';
import user3 from '../static/bootstrap/images/user3.png';
import Head from './nav/Head.js';



// import '../static/css/app.css'; // 导入 CSS 文件
// import '../static/indexcss/aacsss.css';
function formatDate(timestamp) {
    if (timestamp) {
        const date = new Date(Number(timestamp) * 1000); // 将BigInt转换为Number后再进行计算
        return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
    }
    return '';
}
const Reviewer_MaterialList = () => {
    // 使用 useParams 获取路由参数中的地址信息
    const { address } = useParams();
    const [web3, setWeb3] = useState(null);
    const [contractReviewerList, setcontractReviewerList] = useState(null);
    const [contractReviewer, setcontractReviewer] = useState(null);
    const [isReviewer, setisReviewer] = useState(false);
    const [contractUserList, setContractUserList] = useState(null);
    const [contractMaterialList, setcontractMaterialList] = useState(null);
    const [materialId, setMaterialId] = useState('');
    const [userAddress, setUserAddress] = useState('');
    const [activityId, setActivityId] = useState('');
    const [contribution, setContribution] = useState('');
    const [materialRecords, setMaterialRecords] = useState([]);//返回的数据数组
    const [IsList, setIsList] = useState(false);//控制是否显示列表
    const [categoryFilter, setCategoryFilter] = useState('');//用于通过分类查询
    const [deleteModalOpen, setDeleteModalOpen] = useState(false);
    const columns = [
        {
            title: '材料ID',
            dataIndex: 'id',
            key: 'id',
            render: (text) => {
                const newText = text.toString(); // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },
        },
        {
            title: '用户地址',
            dataIndex: 'user',
            key: 'user',
            render: (text) => {
                const newText = text.toString(); // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },
        },
        {
            title: '材料文件名',
            dataIndex: ['userMaterial', 'materialName'],
            key: 'materialName',
            render: (text) => (
                <span style={{ color: 'black' }}>
                    {text}
                </span>
            )
        },
        {
            title: '材料描述',
            dataIndex: ['userMaterial', 'description'],
            key: 'description',
            render: (text) => (
                <span style={{ color: 'black' }}>
                    {text}
                </span>
            )
        },
        {
            title: '上传时间',
            dataIndex: 'uploadTime',
            key: 'uploadTime',
            render: (text) => (
                <span style={{ color: 'black' }}>{formatDate(text)}</span>
            ),
        },
        {
            title: '审核员地址',
            dataIndex: 'reviewer',
            key: 'reviewer',
            render: (text) => {
                const newText = text.toString(); // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },
        },
        {
            title: '审核时间',
            dataIndex: 'reviewTime',
            key: 'reviewTime',
            render: (text) => (
                <span style={{ color: 'black' }}>{formatDate(text)}</span>
            ),
        },
        {
            title: '积分奖励',
            dataIndex: 'points',
            key: 'points',
            render: (text) => {
                const newText = text.toString(); // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },
        },
        {
            title: '层次等级',
            dataIndex: ['userMaterial', 'layer'],
            key: 'layer',
            render: (text) => {
                const newText = text.toString(); // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },

        },
        {
            title: '获奖等级',
            dataIndex: ['userMaterial', 'reward'],
            key: 'reward',
            render: (text) => {
                const newText = text.toString(); // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },

        },
        {
            title: '审核状态',
            dataIndex: 'isReviewed',
            key: 'isReviewed',
            render: (text) => (
                <span style={{ color: 'black' }}>{text == true ? '已审核' : '未审核'}</span>
            ),
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <button className="btn btn-primary btn-lg d-block w-100" type="primary" onClick={() => openDeleteModal(record)}>
                    审核
                </button>
            ),
        }

    ];
    useEffect(() => {
        async function init() {
            // 连接到以太坊网络
            if (window.ethereum) {
                const web3Instance = new Web3(window.ethereum);
                try {
                    // 请求用户授权
                    await window.ethereum.enable();
                    setWeb3(web3Instance);


                    // 创建材料列表合约实例
                    const materialListInstance = new web3Instance.eth.Contract(
                        MaterialListABI,
                        MaterialListAddress
                    );
                    setcontractMaterialList(materialListInstance);
                    // 创建审核员合约实例
                    const reviewerInstance = new web3Instance.eth.Contract(
                        ReviewerABI,
                        address
                    );
                    setcontractReviewer(reviewerInstance);
                    // 创建用户列表合约实例
                    const userListInstance = new web3Instance.eth.Contract(
                        UserListABI,
                        UserListAddress
                    );
                    setContractUserList(userListInstance);
                    // 创建审核员列表合约实例
                    const reviewerListInstance = new web3Instance.eth.Contract(
                        ReviewerListABI,
                        ReviewerListAddress
                    );
                    setcontractReviewerList(reviewerListInstance);
                    // 获取当前用户的以太坊账户地址
                    const accounts = await web3Instance.eth.getAccounts();
                    const currentAddress = accounts[0];
                    // 获取用户合约的 owner 地址
                    const ownerAddress = await reviewerInstance.methods.getOwner().call();
                    // 检查当前账户是否是用户本人
                    setisReviewer(currentAddress === ownerAddress);

                    // 自动获取学生信息列表
                    await selectAllMateriaList(web3Instance, materialListInstance);
                } catch (error) {
                    console.error(error);
                }
            } else {
                console.error('请安装以太坊浏览器插件，如 MetaMask');
            }
        }
        init();
    }, [address]);

    //打开更新模态框
    const openDeleteModal = (material) => {
        setMaterialId(material.materialId);
        setUserAddress(material.userAddress)
        setActivityId(material.activityId)
        setContribution(material.contribution)
        setDeleteModalOpen(true);

    };

    // 获取所有材料列表函数
    const selectAllMateriaList = async (web3Instance, materialListInstance) => {
        if (materialListInstance) {
            try {
                // 获取当前用户的以太坊账户地址
                const accounts = await web3Instance.eth.getAccounts();
                const fromAddress = accounts[0];
                await materialListInstance.methods.SelectAllMateriaList().call({ from: fromAddress }).then(
                    (result) => {
                        console.log("material records", result);
                        setMaterialRecords(result); // 更新 materialRecords 数组
                        setIsList(true);//让列表显示出来
                    })

            } catch (error) {
                console.log(error)
                alert('查询失败');
            }
        }
    };
    // 审核员审核材料函数
    const RevieMaterial = async () => {
        setDeleteModalOpen(false);
        if (contractMaterialList) {
            try {
                // 获取当前用户的以太坊账户地址
                const accounts = await web3.eth.getAccounts();
                const fromAddress = accounts[0];
                // 查询材料记录以检查是否已经审核  
                const materialRecord = await contractMaterialList.methods.materialRecords(materialId).call({ from: fromAddress });
                console.log("materialRecord", materialRecord);
                if (materialRecord.isReviewed == true) {
                    alert('该材料已经被审核！');
                    return; // 退出函数，不执行后续审核逻辑  
                }
                const userContractAddr = await contractUserList.methods.getUserAddress(userAddress).call({ from: fromAddress });
                console.log("userContractAddr", userContractAddr)
                console.log("fromAddress:", fromAddress, "Input", materialId, ReviewerListAddress, address, userContractAddr, ActivityListAddress, activityId, contribution);
                await contractMaterialList.methods.reviewMaterial(materialId, ReviewerListAddress, address, userContractAddr, ActivityListAddress, activityId, contribution).send({ from: fromAddress });
                alert("审核完成！")
            } catch (error) {
                console.error(error);
                alert('审核失败！');
            }
        }
    };
    const handleFilterActivity = async () => {
        if (contractMaterialList) {
            try {
                const filteredActivityList = materialRecords.filter((activity) => activity.materialName === categoryFilter);//设置通过类别查询
                setMaterialRecords(filteredActivityList);

                setIsList(true);
            } catch (error) {
                console.error(error);
            }
        }
    };
    return (
        <div>
            {/* 如果当前账户不是审核员，则显示提示信息 */}
            {!isReviewer && (<div>您没有权限访问此页面。</div>)}

            {/* 审核员界面 */}
            {isReviewer && (
                <div className="page-wrapper" style={{
                    backgroundColor: '#FFFFFF'
                }}>
                    <div className="main-container">
                        <ReviewerNavBar address={address} />

                        <div className="app-container">
                            <Head></Head>
                            <div className="app-body">
                                <div className="container-fluid">

                                    <div>
                                        <main className="page hire-me-page">
                                            <section className="portfolio-block hire-me">

                                                <div className="container">
                                                    <div className="border rounded border-0 shadow-lg p-3 p-md-10"
                                                        data-bs-theme="light"
                                                        style={{
                                                            backgroundColor: 'rgba(36, 36, 41, 0.6)'
                                                        }}
                                                    >
                                                        <div className="mb-3">
                                                            <h2>查询所有材料</h2>
                                                            <div className="d-flex justify-content-end mt-7">
                                                                <div className="input-group mb-3" style={{ maxWidth: '300px' }}>
                                                                    <input
                                                                        type="text"
                                                                        className="form-control"
                                                                        placeholder="输入材料文件名查询"
                                                                        aria-label="材料文件名查询"
                                                                        aria-describedby="basic-addon2"
                                                                        value={categoryFilter}
                                                                        onChange={(e) => setCategoryFilter(e.target.value)}
                                                                    />
                                                                    <div className="input-group-append">
                                                                        <button className="btn btn-primary btn-lg d-block w-100" type="button" onClick={handleFilterActivity}>搜索</button>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            {IsList ? (
                                                                <Table
                                                                    dataSource={materialRecords}
                                                                    columns={columns} // 确保你已经定义了columns
                                                                    pagination={{
                                                                        pageSize: 2,
                                                                        showTotal: false, // 隐藏总页数
                                                                        showSizeChanger: false, // 隐藏页面大小选择器
                                                                        itemRender: (current, type, originalElement) => (
                                                                            <span style={{ color: 'black' }}>
                                                                                {current}
                                                                            </span>
                                                                        ),
                                                                    }}                                                //  onRow={onRow} // 确保你传递了onRow函数，用于保存对应的id
                                                                />
                                                            ) : (
                                                                <div>No activity information available.</div>
                                                            )}


                                                            {deleteModalOpen && (
                                                                <div className="mb-3">
                                                                    <h2>审核材料</h2>

                                                                    <div className="mb-3">
                                                                        <label className="form-label" >材料ID</label>
                                                                        <input className="form-control item" type="text" placeholder="材料id" value={materialId} onChange={(e) => setMaterialId(e.target.value)} />
                                                                    </div>

                                                                    <div className="mb-3">
                                                                        <label className="form-label" >用户账户地址</label>
                                                                        <input className="form-control item" type="text" placeholder="用户账户地址" value={userAddress} onChange={(e) => setUserAddress(e.target.value)} />
                                                                    </div>

                                                                    <div className="mb-3">
                                                                        <label className="form-label" >活动ID</label>
                                                                        <input className="form-control item" type="text" placeholder="活动id" value={activityId} onChange={(e) => setActivityId(e.target.value)} />
                                                                    </div>

                                                                    <div className="mb-3">
                                                                        <label className="form-label" >贡献度</label>
                                                                        <input className="form-control item" type="text" placeholder="贡献度" value={contribution} onChange={(e) => setContribution(e.target.value)} />
                                                                    </div>

                                                                    <div className="mb-3 mt-4">
                                                                        <button className="btn btn-primary btn-lg d-block w-100" onClick={RevieMaterial}>审核</button>
                                                                    </div>


                                                                </div>
                                                            )}
                                                        </div>
                                                    </div>
                                                </div>

                                            </section>
                                        </main>
                                    </div>


                                </div>
                            </div>
                            <div className="app-footer">
                                <span>
                                    © Bootstrap Gallery 2023
                                </span>
                            </div>
                        </div>
                    </div>

                </div>
            )}
        </div>
    );
}

export default Reviewer_MaterialList;
